/**
 * Copyright (c) 2017. 北京江融信科技有限公司 版权所有
 * Created on 17/9/7.
 */

package com.sample.springbatch.job.config;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.job.builder.FlowBuilder;
import org.springframework.batch.core.job.flow.Flow;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;


/**
 * created by wangshuguan
 */
@Configuration
public class ParallelStepConfig extends BaseConfig {

    @Bean(name = "parallelStepJob" )
    public Job job() {
        return jobBuilderFactory.get("parallelStepJob")//job名称
                .start(flow())
                .split(new SimpleAsyncTaskExecutor())
                .add(flow1())
                .end()
                .build();
    }


    @Bean
    public Flow flow() {
        return new FlowBuilder<Flow>("flow").start(step()).build();
    }

    @Bean
    public Flow flow1() {
        return new FlowBuilder<Flow>("flow1").start(step1()).build();
    }


    @Bean
    public Step step() {
        return stepBuilderFactory.get("step")
                .tasklet(tasklet())
                .build();
    }

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1")
                .tasklet(tasklet())
                .build();
    }


    @Bean
    public Tasklet tasklet() {
        return new SampleTasklet();
    }

    public class SampleTasklet implements Tasklet {

        @Override
        public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
            for (int i = 0; i < 20; i++) {

                System.out.println("*********************");
                System.out.println("execute step" +  chunkContext.getStepContext().getStepName() + ", execute thread: " + Thread.currentThread().getName() + ", seq: "+ i);

            }

            return RepeatStatus.FINISHED;
        }
    }

}
